package com.vivo.java.java2d.doublebuffered;

import java.awt.Frame;
import java.awt.Graphics;
import java.awt.RenderingHints;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

public class DoubleBufferDemo extends Frame {

	/**
         * 
         */
        private static final long serialVersionUID = 1L;

	public DoubleBufferDemo() {
		Dbpanel p = new Dbpanel();
		p.setSize(300, 300);
		this.add(p);
		this.setBounds(10, 10, 500, 500);
		this.setVisible(true);
		for (int i = 0; i < 1000; i++) {
			p.animateToTheRight();
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// close
		this.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent evt) {
				dispose();
				System.exit(0);
			}

		});
	}

	public static void main(String[] args) {
		DoubleBufferDemo m = new DoubleBufferDemo();
		m.setVisible(true);
	}

}

class Dbpanel extends DoubleBufferPanel {

	/**
         * 
         */
        private static final long serialVersionUID = 1L;
	// class variables
	private int posX;
	private BufferedImage imagePIC = null;

	public Dbpanel() {
		super();

		posX = 0;
		// 读取需要的image
		File image = new File("resource/role.jpg");
		try {
			imagePIC = ImageIO.read(image);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void animateToTheRight() {
		// this can be called from everywhere, anytime
		posX++;
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		repaint();
	}

	// attention: we don't touch update() and paint() anymore
	// we use paintbuffer() instead
	public void paintBuffer(Graphics g) {
		// / g is the offscreen graphics
		AffineTransform tx = new AffineTransform();
		tx.translate(1, 1);
		tx.rotate(1, 50, 50);
		Map rhmap = new HashMap();
		rhmap.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		rhmap.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		// rhmap.put(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
		// rhmap.put(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

		RenderingHints rh = new RenderingHints(rhmap);
		AffineTransformOp op = new AffineTransformOp(tx, rh);
		imagePIC = op.filter(imagePIC, null);
		
		g.drawImage(imagePIC, posX, 20, null);
	}

}
